package com.why.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.why.properties.JwtProperties;
import com.why.utils.JwtUtil;
import com.why.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //校验jwt
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(JwtProperties.adminTokenName);

        //1.2、校验令牌是否为空
        if (token == null || token.trim().isEmpty()) {
            // 令牌为空，设置响应状态为 403 并提示非法登录
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            throw new RuntimeException("非法登录");
        }

        //2、校验令牌
        try {
            //从redis中获取token
            String tokenByRedis = stringRedisTemplate.opsForValue().get(token);
            System.out.println("---------tokenByRedis:"+tokenByRedis);
            if (tokenByRedis == null || tokenByRedis.equals("")){
                //token已经失效了 --- 401
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                throw new RuntimeException("JWT失效");
            }


            log.info("jwt校验:{}", token);
            Map<String, Object> claims = JwtUtil.parseToken(token);

            //将业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);

            //3、通过，放行
            return true;
        }  catch (JWTVerificationException exception) {
            if (exception instanceof com.auth0.jwt.exceptions.TokenExpiredException) {
                // JWT 过期异常处理
                response.setStatus(401);
                throw new RuntimeException ("JWT过期", exception);
            } else {
                // 非法访问异常处理
                response.setStatus(401);
                throw new RuntimeException(" 非法访问", exception);
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
